#include <stdio.h>
#include <string.h>
#include "calist.h"

static int list_seed=1;

void lkinit(lklist* plist)
{
	plist->seed = ++list_seed+1;

	plist->prev = plist;
	plist->next = plist;
}


// add item to end of list.
void lkadd(lklist* plist, lklist* item)
{
	if(item->seed == plist->seed)
	{
		fprintf(stderr, "### Error: invalid item, already member in list ??? \n");
		return;
	}
	
	lklist *pitem = (lklist*)item;
	pitem->next = plist;
	pitem->prev = plist->prev;

	plist->prev->next = pitem;
	plist->prev = pitem;

	pitem->seed = plist->seed;
}


//void lkins(lklist* pdest, lklist* pitem)
void lkins(lklist* pdest, lklist* pitem)
{
	if(pdest->seed == pitem->seed)
	{
		fprintf(stderr, "### Error: invalid item, already member in list ??? \n");
		return;
	}


	lklist* oldnext = pdest->next;
	pdest->next = pitem;
	pitem->prev = pdest;
	pitem->next = oldnext;

	pitem->seed = pdest->seed;
}

void lkdel(lklist *pitem)
{
	
	if(pitem->seed==0) 
	{
		fprintf(stderr, "### Error: list item is not valid...\n");
		return;
	}
	
	pitem->prev->next = pitem->next;
	pitem->next->prev = pitem->prev;
//	pitem->prev = pitem->next = NULL;
	
	pitem->seed = 0;
}


void *lknext(lklist* pitem)
{
	if(pitem->next == pitem)
		return NULL;
	return pitem->next;
}

// p: 
lklist* lkpop_head(lklist * pitem)
{
	lklist* next = pitem->next;
	lkdel(pitem);
	if(next->seed == 0)
		return NULL;
	return next;
}


lklist* lkpop_tail(lklist* list)
{
	if(list->seed == 0)
		return NULL;
	lklist* pitem = list->prev;
	lkdel(list->prev);
	return pitem;
}



void lkqueInit(lkque* ptr)
{
	memset(ptr, 0, sizeof(lkque));
};

void lkqueAdd(lkque* q, lklist* item)
{
	if(q->pstart==NULL)
	{
		q->pstart = item;
		q->count = 1;
		lkinit(item);
	}
	else
	{
		q->count++;
		lkadd(q->pstart, item);
	}
			
}

lklist* lkqueGet(lkque* q)
{
	lklist* ret;
	if(q->count > 0)
	{
		q->count--;
		ret = q->pstart;
		q->pstart = (lklist*)lkpop_head(q->pstart);
		return ret;
	}
	else
		return NULL;
}



